package devboard.dbutil;

import java.io.IOException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class MongoUtil {
	/*private static final String HOST="mongodb.devboard.jelastic.com";
	private static final int PORT=27017;
	private static final String USERNAME="yira";
	private static final String PASSWD="7JYewgf_2wfec3";
	private static final String DBNAME="devboard";*/
	
	
	private static final String HOST="localhost";
	private static final int PORT=27017;
	private static final String USERNAME="";
	private static final String PASSWD="";
	private static final String DBNAME="devboard";
	
	private static Mongo mongo; 
	private static DB db;
	
	public static DBCollection getCollection(String name) throws  IOException {
		if((mongo==null)||(db==null)){
			createConnection();
		}
		return db.getCollection(name);
	}
	
	public static void createConnection() throws  IOException {
		mongo=new Mongo(HOST, PORT);
		db=mongo.getDB(DBNAME);
		if(!USERNAME.equals("")){
			if(db.authenticate(USERNAME, PASSWD.toCharArray())){
				System.out.println("------------authenticated!!!");
			}else{
				throw new IOException("not authenticated");
			}
		}
	}
	
	public static void sendMessage(String text, String owner, String ownerId) throws IOException{
		DBCollection chat=getCollection("Chat");
		BasicDBObject message=new BasicDBObject();
		message.put("text", text);
		message.put("time", System.currentTimeMillis());
		message.put("ownerId", ownerId);
		message.put("owner", owner);
		chat.insert(message);
	}
	
	/*public static void closeConnection() {
		mongo.close();
		mongo=null;
	}*/
}
